#include "CSprite.h"
#include "trace.h"


LPD3DXSPRITE CSprite::_spriteHander;
void CSprite::InitSpriteHander(D3DXGraphic *gfx)
{
	D3DXCreateSprite(gfx->pDevice, &_spriteHander);
}

CSprite::CSprite(LPSTR FilePath, int Width, int Height, int index, int Count, int SpritePerRow, int alpha, bool isAlpha, D3DCOLOR transparent)
{
	_image = LoadTexture(FilePath, transparent);

	_width = Width;
	_height = Height;
	_count = Count;
	_index = index;
	_spritePerRow = SpritePerRow;
	

	_isChangeAlpha = isAlpha;
	_alpha = alpha;
}

void CSprite::Render(float x, float y)
{
	RECT srect;
	srect.left = _index*_width;
	srect.top = 0;
	srect.right = srect.left + _width;
	srect.bottom = _height;

	D3DXVECTOR3 position((float)x, (float)y, 0.0f);

	D3DXMATRIX mt;
	D3DXMatrixIdentity(&mt);

													//  1	 0	  0	  0
	mt._22 = -1.0f;									//  0   -1	  0	  0
	mt._41 = -0;									//  0	 0	  1	  0
	mt._42 = CCamera::GetInstance()->GetTop();		// -x0	 y0	  0	  1

	D3DXVECTOR4 vp_pos;
	D3DXVec3Transform(&vp_pos, &position, &mt);

	D3DXVECTOR3 p(vp_pos.x, vp_pos.y, 0.0f);
	D3DXVECTOR3 center((float)_width / 2, (float)_height / 2, 0.0f);

	int color = 255;
	if (_isChangeAlpha)
	{
		color = rand() % 155 + 100;
	}

	_spriteHander->Begin(D3DXSPRITE_ALPHABLEND);

	_spriteHander->Draw(_image,
		&srect,
		&center,
		&p,
		D3DCOLOR_ARGB(_alpha, color, color, color));	// need

	_spriteHander->End();
}

void CSprite::Next()
{
	if (_index > _spritePerRow)
		_index = 0;
	_index++;
}

void CSprite::Reset()
{
	_index = 0;
}

CSprite::~CSprite()
{
	_image->Release();
}

void CSprite::ChangeAlpha(bool changeAlpha)
{
	_isChangeAlpha = changeAlpha;
}

LPDIRECT3DTEXTURE9 CSprite::LoadTexture(LPCSTR filePath, D3DCOLOR transcolor)
{
	LPDIRECT3DTEXTURE9 texture = NULL;
	D3DXIMAGE_INFO info;
	LPDIRECT3DDEVICE9 d3ddv;
	_spriteHander->GetDevice(&d3ddv);
	HRESULT result = D3DXGetImageInfoFromFileA(filePath, &info);
	if (result != D3D_OK)
	{
		trace(L"[ERROR] Failed to get information from image file '%s'", filePath);
		return NULL;
	}
	result = D3DXCreateTextureFromFileExA(
		d3ddv,
		filePath,
		info.Width,
		info.Height,
		1,
		D3DPOOL_DEFAULT,
		D3DFMT_UNKNOWN,
		D3DPOOL_DEFAULT,
		D3DX_DEFAULT,
		D3DX_DEFAULT,
		transcolor,			// transparent color
		&info,
		NULL,
		&texture);
	if (result != D3D_OK)
	{
		trace(L"[ERROR] Failed to create texture from file '%s'", filePath);
		return NULL;
	}
	return texture;
}